import json

from django.core import serializers
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from rest_framework import generics, filters
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from .serializers import Submit_ZhuangBeiSerializer, Jineng_Attrs_Serializer, Jineng_Serializer, RW_JN_Serializer
from .serializers import ZhuangBei_Serializer, RW_ZB_Serializer
from ..models import *

from my_example import Attribute_Evaluation
from .thread import ComputeThread

# 提交装备
class ApplyList(generics.ListCreateAPIView):
    queryset = Submit_ZhuangBei.objects.all()
    serializer_class = Submit_ZhuangBeiSerializer


class ApplyDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Submit_ZhuangBei.objects.all()
    serializer_class = Submit_ZhuangBeiSerializer


# 装备/技能属性

class AttrList(generics.ListCreateAPIView):
    queryset = jineng_attrs.objects.all()
    serializer_class = Jineng_Attrs_Serializer


class AttrDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = jineng_attrs.objects.all()
    serializer_class = Jineng_Attrs_Serializer


# 技能
class JinengList(generics.ListCreateAPIView):
    queryset = jineng.objects.all()
    serializer_class = Jineng_Serializer

    filter_backends = (filters.SearchFilter,)
    search_fields = ('zhiye',)


class JinengDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (IsAuthenticated,)
    queryset = jineng.objects.all()
    serializer_class = Jineng_Serializer


# 装备
class ZhuangBeiList(generics.ListAPIView):
    queryset = zhuangbei.objects.all()
    serializer_class = ZhuangBei_Serializer

    filter_backends = (filters.SearchFilter,)
    search_fields = ('leixing', 'name')


class ZhuangBeiDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = zhuangbei.objects.all()
    serializer_class = ZhuangBei_Serializer


class CH_View(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self,request):
        '''
        获取所有的称号
        :param request:
        :return:
        '''
        chs=list(chenghao.objects.all().values("name","pk"))
        print(chs)
        return JsonResponse({'code': 200, 'message': '请求成功', 'data': chs})
    def post(self,request):
        ren = request.user.game_user
        ch_pk=request.data['pk']
        ren.chenghao=chenghao.objects.get(pk=ch_pk)
        ren.save()
        # 更新属性
        Attribute_Evaluation.liliang_result(ren)
        Attribute_Evaluation.minjie_result(ren)
        Attribute_Evaluation.ganzhi_result(ren)
        Attribute_Evaluation.zhili_result(ren)
        return JsonResponse({'code': 200, 'message': '修改成功'})


class RW_ZB_View(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        data = request.data
        pk= self.request.user.game_user.pk
        leixing=data['leixing']
        zb=get_object_or_404(zhuangbei,pk=data['zhuangbei'])
        print(pk,leixing,zb)
        try:
            result=renwu_zhuangbei.objects.filter(Q(renwu=pk) & Q(zhuangbei__leixing=leixing))
            if not result.exists():
                ren=get_object_or_404(renwu,pk=pk)
                renwu_zhuangbei(renwu=ren,zhuangbei=zb).save()
                return JsonResponse({'code': 200, 'message': '请求成功', 'data': "添加成功"})

            item=result.get()
            item.zhuangbei=zb
            item.save()

            ren = renwu.objects.get(pk=pk)
            Attribute_Evaluation.liliang_result(ren)
            Attribute_Evaluation.minjie_result(ren)
            Attribute_Evaluation.ganzhi_result(ren)
            Attribute_Evaluation.zhili_result(ren)

            return JsonResponse({'code': 200, 'message': '请求成功', 'data': "更换成功"})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'message': '请求成功', 'data': "添加出错,"+str(e)})





class RW_TYPEJN_View(APIView):
    # 需要登录
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        '''
        人物绑定技能
        :param request:json格式
        {
            "type":"职业"
            "jns":[]
        }
        :return:
        '''
        data = request.data
        ren = self.request.user.game_user.pk
        type = data['type']

        # 解绑没有的
        all_jn_for_zhiye = set(jineng.objects.filter(zhiye=type).values_list("pk", flat=True))
        # 获取差集
        cj_jn = all_jn_for_zhiye - set(data['jns'])
        # 获取人物已经绑定的
        bind_jns = renwu_jieng.objects.filter(Q(renwu=ren) & Q(jineng__in=cj_jn)).values_list("jineng", flat=True)

        # 批量删除已经数据
        renwu_jieng.objects.filter(Q(renwu=ren) & Q(jineng__in=list(bind_jns))).delete()

        # 绑定有的
        for jn in data['jns']:
            item = {}
            item['renwu'] = self.request.user.game_user.pk
            item['jineng'] = jn
            item = RW_JN_Serializer(data=item)
            print(item)
            # 如果有数据不合法
            if not item.is_valid():
                return JsonResponse({'code': 200, 'message': '请求成功', 'data': "数据不合法"})
            print(renwu_jieng.objects.filter(Q(renwu=self.request.user.game_user) & Q(jineng=jn)).count())
            # 如果人物已经绑定技能,跳过
            if renwu_jieng.objects.filter(Q(renwu=self.request.user.game_user) & Q(jineng=jn)).count() != 0:
                continue

            # 数据保存到数据库中
            item.save()
        # 更新属性
        ren=renwu.objects.get(pk=ren)
        Attribute_Evaluation.liliang_result(ren)
        Attribute_Evaluation.minjie_result(ren)
        Attribute_Evaluation.ganzhi_result(ren)
        Attribute_Evaluation.zhili_result(ren)

        return JsonResponse({'code': 200, 'message': '请求成功', 'data': "添加成功"})

    def get(self, request):
        type = request.GET.get("type")
        ren = self.request.user.game_user.pk

        # 获取该职业所有技能
        all_jn_for_zhiye = jineng.objects.filter(zhiye=type).values_list('pk', flat=True)

        # 获取人物已经绑定的
        data = list(
            renwu_jieng.objects.filter(Q(renwu=ren) & Q(jineng__in=all_jn_for_zhiye)).values_list("jineng", flat=True))

        return JsonResponse({'code': 200, 'message': '请求成功', 'data': data})


class RW_JN_View(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        ren = self.request.user.game_user
        skills = renwu_jieng.objects.filter(renwu=ren).all()
        data = []
        for skill in skills:
            d = {}
            d['name'] = skill.jineng.name
            d['zhiye_name'] = skill.jineng.zhiye_name
            d['attrs_content'] = skill.jineng.attrs_content
            data.append(d)
        return JsonResponse(data, safe=False)


class RW_MB_View(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        ren = request.user.game_user

        thread_dict={}
        func_list=[
            [Attribute_Evaluation.pikan_result, 'pikan'],
                   [Attribute_Evaluation.chuanci_result,'chuanci'],
                   [Attribute_Evaluation.mogong_result,'mogong'],
                    [Attribute_Evaluation.wushang_result,"wushang"],
                   [Attribute_Evaluation.gongci_result,'gongci'],
                   [Attribute_Evaluation.pojia_result,'pojia'],
                   [Attribute_Evaluation.moming_result,'moming'],
                   [Attribute_Evaluation.mingzhong_result,'mingzhong'],
                   [Attribute_Evaluation.mochuan_result,'mochuan'],
                   [Attribute_Evaluation.zhiming_result,'zhiming'],
                   [Attribute_Evaluation.duoshan_result,'duoshan'],
                   [Attribute_Evaluation.dongcha_result,'dongcha'],
                   [Attribute_Evaluation.chushou_result,'chushou'],
                    [Attribute_Evaluation.wushimofan_result,"wushimofan"]

                   ]
        # 创建线程
        for func in func_list:
            t=ComputeThread(func[0],ren)
            thread_dict[func[1]]=t
        # 启动线程
        for key,th in thread_dict.items():
            th.start()

        # 等待线程结束
        for key,th in thread_dict.items():
            th.join()


        renattr=renwuattrs.objects.get(renwu=ren)

        data = {
            "nicheng": ren.name,
            "nums_type": ren.nums_type_name,
            "nums": ren.nums,
            "nums_bf": ren.nums_bf,

            "liliang":renattr.liliang ,
            'minjie': renattr.minjie,
            "zhili": renattr.zhili,
            "ganzhi":renattr.ganzhi ,

            "attrs_data": [

                {
                    "name": "劈砍",
                    "value":thread_dict['pikan'].get_result()
                },
                {
                    "name": "穿刺",
                    "value": thread_dict['chuanci'].get_result()
                }
                ,
                {
                    "name": "魔攻",
                    "value": thread_dict['mogong'].get_result()
                },
                {
                    "name":"武器伤害",
                    "value":thread_dict['wushang'].get_result()
                },
                {
                    "name": "攻次",
                    "value": thread_dict['gongci'].get_result()
                },
                {
                    "name": "破甲",
                    "value": thread_dict['pojia'].get_result()
                },
                {
                    "name": "魔命",
                    "value": thread_dict['moming'].get_result()
                },
                {
                    "name": "命中",
                    "value": thread_dict['mingzhong'].get_result()
                },
                {
                    "name": "魔穿",
                    "value": thread_dict['mochuan'].get_result(),
                },
                {
                    "name": "致命",
                    "value": thread_dict['zhiming'].get_result()
                },
                {
                    "name": "洞察",
                    "value": thread_dict['dongcha'].get_result()
                },
                {
                    "name": "躲闪",
                    "value": thread_dict['duoshan'].get_result()
                },
                {
                    "name": "出手",
                    "value": thread_dict['chushou'].get_result()
                },
                {
                    "name": "无视魔法反馈",
                    "value": thread_dict['wushimofan'].get_result()
                },
                {
                    "name": "格挡",
                    "value": -1
                },

            ]
        }

        return JsonResponse(data, safe=False)


@api_view(['GET', "POST"])
@permission_classes((IsAuthenticated,))
def renwu_info(request):
    if request.method == 'GET':
        ren = request.user.game_user
        data = {
            'name': ren.name,
            "zhiye": ren.zhiye_name,
            "nums": ren.nums,
            'nums_bf': ren.nums_bf,
            "nums_type": ren.nums_type_name,
            "chenghao":ren.chenghao.name,
            "chpk": ren.chenghao.pk
        }
        return JsonResponse({'code': 200, 'message': '请求成功', 'data': data})
    else:
        try:
            data = request.data
            ren = request.user.game_user
            print(ren)
            print(data)
            ren.name = data['name']
            ren.zhiye = data['zhiye']
            ren.nums = int(data['nums'])
            ren.nums_bf = int(data['nums_bf'])
            ren.nums_type = data['nums_type']

            ren.save()
            # 更新人物属性
            Attribute_Evaluation.liliang_result(ren)
            Attribute_Evaluation.minjie_result(ren)
            Attribute_Evaluation.ganzhi_result(ren)
            Attribute_Evaluation.zhili_result(ren)

            msg = "success"
            code = 200
        except Exception as e:
            msg = str(e)
            code = 500
        finally:
            return JsonResponse({'code': code, 'message': msg})


@api_view(['GET'])
def get_zb_types(request):
    data = []
    for leixing in leixings:
        data.append(leixing[1])
    return JsonResponse(data, safe=False)


@permission_classes((IsAuthenticated,))
@authentication_classes((JSONWebTokenAuthentication,))
@api_view(['GET'])
def get_zy_jd_types(request):
    zydata = []
    for zhiye in zhiyes:
        d = {}
        d['name'] = zhiye[1]
        d['value'] = zhiye[0]
        zydata.append(d)
    jddata = []
    for item in types:
        d = {}
        d['name'] = item[1]
        d['value'] = item[0]
        jddata.append(d)

    data = {
        'zhiyes': zydata,
        "jds": jddata
    }
    return JsonResponse(data, safe=False)


@api_view(['GET'])
def get_zb_types2(request):
    data = {}
    for leixing in leixings:
        data[leixing[1]] = leixing[0]
    return JsonResponse(data, safe=False)


@api_view(['GET'])
def get_rwzb(request):
    # 获取人物
    r = request.user.game_user
    # 获取人物装备
    zbs = renwu_zhuangbei.objects.filter(renwu=r).all()
    data = {}
    for zb in zbs:
        data[zb.zhuangbei.leixing] = {}
        data[zb.zhuangbei.leixing]["name"] = zb.zhuangbei.name
        data[zb.zhuangbei.leixing]["content"] = zb.zhuangbei.attrs_content

    return JsonResponse(data, safe=False)

# def get_zb_by_type(request,type_name):
#     # data=[]
#     data=zhuangbei.objects.filter(leixing=type_name).all().
#     return JsonResponse(data,safe=False)
